package Binary::Tree;

our $VERSION = '0.01';

use Moose;

has 'node' => ( is => 'rw', isa => 'Any' );

has 'parent' => (
    is        => 'rw',
    isa       => 'Binary::Tree',
    predicate => 'has_parent',
    weak_ref  => 1,
);

has 'left' => (
    is        => 'rw',
    isa       => 'Binary::Tree',
    predicate => 'has_left',
    lazy      => 1,
    default   => sub { Binary::Tree->new( parent => $_[0] ) },
    trigger   => \&_set_parent_for_child
);

has 'right' => (
    is        => 'rw',
    isa       => 'Binary::Tree',
    predicate => 'has_right',
    lazy      => 1,
    default   => sub { Binary::Tree->new( parent => $_[0] ) },
    trigger   => \&_set_parent_for_child
);

sub _set_parent_for_child {
    my ( $self, $child ) = @_;

    confess "You cannot insert a tree which already has a parent"
        if $child->has_parent;

    $child->parent($self);
}

sub traverse {
    my $self = shift;
    my @toret;
    push @toret, $self->left->traverse() if $self->has_left;
    push @toret, \$self;
    push @toret, $self->right->traverse if $self->has_right;
    return @toret;
}

1;
__END__

=head1 NAME

Binary::Tree - Perl extension for defining and managing nodes of a binary tree

=head1 SYNOPSIS

  use Binary::Tree;

=head1 DESCRIPTION

  Definition of a Moose class that can be used to create binary trees.

=head2 EXPORT

  None by default.

=head1 AUTHOR

Alejandro Tejera Pérez, alu3869

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2011 by Alejandro Tejera Pérez

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.10.1 or,
at your option, any later version of Perl 5 you may have available.

=cut
